<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="深入理解java虚拟机,">










<meta name="description" content="概述java类编译成class后我们就没有办法再来影响jvm虚拟机了,    所以java中的大部分看似很灵活的特性编译成字节码后都是最基本的特性, 比如泛型就是Object,  枚举类就是final类,  常量就会替换成具体值, 注解就是一个接口.  等等这些特性都是通过改变字节码的生成来实现的,  也有很多的字节码操作库来控制生成字节码 来达到很多不可思议的功能,  比如Groovy的动态语言">
<meta name="keywords" content="深入理解java虚拟机">
<meta property="og:type" content="article">
<meta property="og:title" content="类加载机制与执行子系统的案例">
<meta property="og:url" content="https://blog.xiezc.xyz/2019/04/08/类加载机执行子系统的案例与实战/index.html">
<meta property="og:site_name" content="xiezc的小站">
<meta property="og:description" content="概述java类编译成class后我们就没有办法再来影响jvm虚拟机了,    所以java中的大部分看似很灵活的特性编译成字节码后都是最基本的特性, 比如泛型就是Object,  枚举类就是final类,  常量就会替换成具体值, 注解就是一个接口.  等等这些特性都是通过改变字节码的生成来实现的,  也有很多的字节码操作库来控制生成字节码 来达到很多不可思议的功能,  比如Groovy的动态语言">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://images2018.cnblogs.com/blog/137084/201805/137084-20180526104342525-959933190.png">
<meta property="og:updated_time" content="2019-04-08T15:43:33.368Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="类加载机制与执行子系统的案例">
<meta name="twitter:description" content="概述java类编译成class后我们就没有办法再来影响jvm虚拟机了,    所以java中的大部分看似很灵活的特性编译成字节码后都是最基本的特性, 比如泛型就是Object,  枚举类就是final类,  常量就会替换成具体值, 注解就是一个接口.  等等这些特性都是通过改变字节码的生成来实现的,  也有很多的字节码操作库来控制生成字节码 来达到很多不可思议的功能,  比如Groovy的动态语言">
<meta name="twitter:image" content="https://images2018.cnblogs.com/blog/137084/201805/137084-20180526104342525-959933190.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://blog.xiezc.xyz/2019/04/08/类加载机执行子系统的案例与实战/">





  <title>类加载机制与执行子系统的案例 | xiezc的小站</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?8ae02d8cf311eabbae2621ff2d51a260";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">xiezc的小站</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">xiezc的小站</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://blog.xiezc.xyz/2019/04/08/类加载机执行子系统的案例与实战/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="xiezc">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="xiezc的小站">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">类加载机制与执行子系统的案例</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-04-08T22:19:47+08:00">
                2019-04-08
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2019/04/08/类加载机执行子系统的案例与实战/" class="leancloud_visitors" data-flag-title="类加载机制与执行子系统的案例">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><p>java类编译成class后我们就没有办法再来影响jvm虚拟机了,    所以java中的大部分看似很灵活的特性编译成字节码后都是最基本的特性, 比如泛型就是Object,  枚举类就是final类,  常量就会替换成具体值, 注解就是一个接口.  等等这些特性都是通过改变字节码的生成来实现的,  也有很多的字节码操作库来控制生成字节码 来达到很多不可思议的功能,  比如Groovy的动态语言特性 ,   也可以通过自定义类加载器来控制类的行为</p>
<h2 id="tomcat正统的类加载器结构"><a href="#tomcat正统的类加载器结构" class="headerlink" title="tomcat正统的类加载器结构"></a>tomcat正统的类加载器结构</h2><p>主流的web服务器都实现类自己的类加载器, 这是因为web服务需要解决如下的功能: </p>
<ul>
<li>部署在同一个服务器上的两个服务的应用类需要相互隔离, 即使他们的类名, 包名完全一样也要隔离. </li>
<li>同一服务器上的两台应用要共用基本的java类库和 一些共用的公共类库.</li>
<li>服务器要保证自己本身的java类的安全不受web服务的影响</li>
<li>支持JSP的应用大部分需要支持HotSwap功能</li>
</ul>
<p>由于上述问题, 自定义类加载器 就是最佳的解决方法</p>
<ol>
<li>放在tomcat中把jar包放入/common 目录 就是所有web和tomcat共享的java类</li>
<li>放在/server 目录,  是tomcat独享的java类</li>
<li>放在/share 是被所有的web 共享但是对tomcat隔离</li>
<li>放在/WebApp/WEB-INF ,  类库仅仅对所放的web服务可见, 对其他web和tomcat隔离</li>
</ol>
<p>tomcat的类加载器图</p>
<p><img src="https://images2018.cnblogs.com/blog/137084/201805/137084-20180526104342525-959933190.png" alt="img"> </p>
<p>图中的 Common类加载器就是加载common目录中的类, 因为它是下面加载器的父类,  所以它加载的类是tomcat和web共享的, catalinal类加载器是tomcat独享的.   Shared Classloader 加载类是所有web共享的, </p>
<p>JaspertLoader 加载器只是加载当前的jsp 一个类. 当产生新的jsp的时候吗就会生成新的加载器类区加载,    </p>
<p>当服务器检测到jsp文件修改的时候就会丢弃老的JaspertLoader , 在新创建一个新的 JaspertLoader 实例区加载修改后的文件.  当用户再次访问servlet的时候,  感觉servlet类发生改变了.  实际上是访问了新的类</p>
<h3 id="OSGI灵活的类加载器架构"><a href="#OSGI灵活的类加载器架构" class="headerlink" title="OSGI灵活的类加载器架构"></a>OSGI灵活的类加载器架构</h3><p>OSGI 是Java事实上的模块化标准.  </p>
<blockquote>
<p>java11已经出来了,  java已经推出了自己的官港模块化功能</p>
</blockquote>
<p>java的类加载可以通过 委派的形式来委派 ‘父加载器’ 加载,  而OSGI会根据用户的配置的Export-Package 列表来维护一个 类加载器的委派 关系.  当要加载某个模块需要加载具体的类A的时候, 查找类A的发布者的加载器, 找到后加载它,</p>
<p><strong>缺点</strong></p>
<p>当有循环依赖的时候 容易出现死锁(类加载的时候需要上锁),  有性能消耗,  会出现内存泄漏 </p>
<h4 id="字节码增强"><a href="#字节码增强" class="headerlink" title="字节码增强"></a>字节码增强</h4><p>常见的有ASM, CGLIB, javassist等,  甚至jvm 为了提高反射的效率还会自动生成代理类的字节码. </p>
<p>###运行中的程序 如何执行新的代码</p>
<blockquote>
<p> 线上环境异常, 又无法停止服务, 并且这个异常还没有打印日志. 如果排查解决.   可以提前在程序中写一个远程接收java类并且加载执行的逻辑,  这时候可以写一些类让线上环境执行,  从而查看线上环境的状态. </p>
</blockquote>
<ul>
<li><p>可以写一个JSP文件上传的服务器, 通过浏览器访问来确定问题</p>
</li>
<li><p>通过Script引擎执行脚本来确定问题</p>
<p>通过自定义类加载器来加载自己传入的类,  并且通过反射调用特定的方法来输出信息, 甚至可以HackSystem.out, 由于自定义的类符合双亲委派模型. 所以可以间接通过自己定义的类获得父加载器的加载的类(就是应用的原有类).  并通过反射执行父类的方法. </p>
<blockquote>
<p>很机智的方法, 很聪明的方法, 还棒的方法. veryGood</p>
</blockquote>
</li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/深入理解java虚拟机/" rel="tag"># 深入理解java虚拟机</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/04/03/虚拟机字节码实行引擎/" rel="next" title="虚拟机字节码执行引擎">
                <i class="fa fa-chevron-left"></i> 虚拟机字节码执行引擎
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/04/08/java编译期优化/" rel="prev" title="java的编译器优化">
                java的编译器优化 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">xiezc</p>
              <p class="site-description motion-element" itemprop="description">主要一些技术文章, 有些文章是转载的</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">72</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#概述"><span class="nav-number">1.</span> <span class="nav-text">概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#tomcat正统的类加载器结构"><span class="nav-number">2.</span> <span class="nav-text">tomcat正统的类加载器结构</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#OSGI灵活的类加载器架构"><span class="nav-number">2.1.</span> <span class="nav-text">OSGI灵活的类加载器架构</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#字节码增强"><span class="nav-number">2.1.1.</span> <span class="nav-text">字节码增强</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xiezc</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("eRAHvO0xVYwckgdXIVpfugRG-gzGzoHsz", "57lKp708hde92YeG1xX9MQj1");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

</body>
</html>
